package com.fa4j.demo.book.service.impl;

import com.fa4j.common.base.exception.CommonRequestError;
import com.fa4j.common.base.model.RemoveCmd;
import com.fa4j.demo.book.convert.BookConverter;
import com.fa4j.demo.book.model.Book;
import com.fa4j.demo.book.model.BookCreateCmd;
import com.fa4j.demo.book.model.BookModifyCmd;
import com.fa4j.demo.book.repository.BookRepository;
import com.fa4j.demo.book.service.BookService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

/**
 * 示例书 服务接口实现
 *
 * @since 2025-09-01 18:44:28
 */
@Slf4j
@Service
@Validated
@RequiredArgsConstructor
public class BookServiceImpl implements BookService {

    private final BookRepository bookRepository;
    private final BookConverter bookConverter;

    /**
     * 新增示例书
     *
     * @param cmd 新增参数
     * @return 示例书
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Book create(@Valid BookCreateCmd cmd) {
        Book entity = bookConverter.toEntity(cmd);
        bookRepository.create(entity);
        return entity;
    }

    /**
     * 编辑示例书
     *
     * @param cmd 编辑参数
     * @return 示例书
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Book modify(@Valid BookModifyCmd cmd) {
        Book entity = bookRepository.findById(cmd.getId())
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("示例书"));
        bookConverter.updateEntity(entity, cmd);
        bookRepository.modify(entity);
        return entity;
    }

    /**
     * 删除示例书
     *
     * @param cmd 删除参数
     * @return 示例书
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Book remove(@Valid RemoveCmd<Integer> cmd) {
        Book entity = bookRepository.findById(cmd.getId())
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("示例书"));
        entity.setOperatorId(cmd.getOperatorId());
        bookRepository.remove(entity);
        return entity;
    }

}




